package com.bee.plus.ai.baidu;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.bee.plus.ai.baidu.vo.ResultRoot;
import com.bee.plus.ai.MessagePrepare;
import com.bee.plus.dto.ContentReq;
import com.bee.plus.util.Conversation;
import com.bee.plus.util.ConversationThreadLocal;
import com.bee.plus.util.JsonUtil;
import com.bee.plus.dto.MessageReq;
import com.bee.plus.dto.MessageResp;
import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.schedulers.Schedulers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.List;

/**
 * @author xupei
 */
@Service("baiduAi")
public class BaiduAiServiceImpl extends MessagePrepare   {

    private Logger logger= LoggerFactory.getLogger(BaiduAiServiceImpl.class);

    private static String token="";

    @Autowired
    private BaiduAiManager aiManager;

    @PostConstruct
    private void load(){
        String responseData= HttpUtil.get(aiManager.getTokenUrl());
        BaiduToken tokenVo= JsonUtil.fromJson(responseData, BaiduToken.class);
        token=tokenVo.getAccess_token();
        logger.info("load token end the token is  {} ",tokenVo.getAccess_token());
    }



    @Override
    protected MessageReq preprocessMessage(MessageReq messageReq){
        Conversation conversation= ConversationThreadLocal.getCurrentConversation();
        List<ContentReq> list=storeManger.getDb().getContentHistoryByConversationId(conversation.getConversationId());
        if(list!=null&&list.size()!=0){
            list=list.subList(list.size()-2,list.size());
            list.add(messageReq.getMessages().get(0));
            messageReq.setMessages(list);
        }
        storeManger.getDb().storeChatInfo(messageReq.getMessages().get(messageReq.getMessages().size()-1),conversation.getConversationId());


        return messageReq;
    }

    @Override
    protected MessageResp processMessage(MessageReq messageReq) {

        List messagesList= messageReq.getMessages();

        messageReq.setMessages(messagesList);
        logger.info("baidu ai service req {}",messageReq.toString());
        String data= HttpRequest.post(aiManager.getChatUrlSpeed(token))
                .header("Content-Type","application/json")
                .body(messageReq.toString())
                .execute()
                .body();
        logger.info("baidu ai service resp {}",data);
        ResultRoot resultRoot=JsonUtil.fromJson(data, ResultRoot.class);
        MessageResp messageResp= MessageResp.builder().content(resultRoot.getResult()).role("assistant").build();

        return messageResp;
    }

    @Override
    protected Flowable<MessageResp> processMessageStream(MessageReq messageReq) {
        logger.info("baidu ai service req start ");
        Flowable<MessageResp> messageRespFlowable=  Flowable.create(emitter -> {
            List<ContentReq> messagesList = messageReq.getMessages();
            messageReq.setMessages(messagesList);
            messageReq.setStream(true);
            messageReq.setTemperature(0.8d);
            logger.info("baidu ai service req {}  ", messageReq.toString());
            Schedulers.newThread().scheduleDirect(()->{

                String urlString = aiManager.getChatUrlSpeed(token);
                HttpChatClient client = new HttpChatClient(urlString);
                try{
                    client.sendMessageAndGetResponse( messageReq, new ResponseCallback() {
                        @Override
                        public void onResponse( MessageResp messageResp) {
                            // 处理响应逻辑
                            emitter.onNext(messageResp);
                        }

                        @Override
                        public void onError(Exception e) {
                            // 处理错误逻辑
                            emitter.onError(e);
                        }

                        @Override
                        public void finish(MessageResp messageResp) {
                            emitter.onComplete();
                        }
                    });
                }catch (IOException e){
                    e.printStackTrace();
                    emitter.onError(e);
                }


            });

        }, BackpressureStrategy.BUFFER);


        return messageRespFlowable;
    }


    @Override
    public void storeChatMessage(MessageResp messageResp,Long conversationId) {
        super.postprocessResponse(messageResp,conversationId);
    }
}
